package com.zscat.mallplus.oms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.SysAdminOperLog;
import com.zscat.mallplus.bill.entity.BillDelivery;
import com.zscat.mallplus.bill.mapper.BillDeliveryMapper;
import com.zscat.mallplus.enums.AllEnum;
import com.zscat.mallplus.enums.ConstansValue;
import com.zscat.mallplus.oms.entity.*;
import com.zscat.mallplus.oms.mapper.OmsOrderOperateHistoryMapper;
import com.zscat.mallplus.oms.mapper.OmsOrderSettingMapper;
import com.zscat.mallplus.oms.service.IOmsDeliveryExpressCompanyService;
import com.zscat.mallplus.oms.service.IOmsOrderItemService;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.oms.vo.OmsMoneyInfoParam;
import com.zscat.mallplus.oms.vo.OmsOrderDeliveryParam;
import com.zscat.mallplus.oms.vo.OmsReceiverInfoParam;
import com.zscat.mallplus.oms.vo.OrderCheckInfo;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.DateUtils;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表
 * </p>
 *
 * @author zscat
 * @since 2019-04-19
 */
@Slf4j
@RestController
@Api(tags = "oms", description = "订单表管理")
@RequestMapping("/oms/OmsOrder")
public class OmsOrderController {

    @Resource
    private IOmsOrderService IOmsOrderService;
    @Resource
    private OmsOrderOperateHistoryMapper omsOrderOperateHistoryMapper;
    @Resource
    private OmsOrderSettingMapper omsOrderSettingMapper;
    @Resource
    private BillDeliveryMapper billDeliveryMapper;
    @Resource
    private IOmsOrderItemService orderItemService;
    @Resource
    private IOmsDeliveryExpressCompanyService omsDeliveryExpressCompanyService;

    /**
     * 对账单详情
     *
     * @return
     */
    @GetMapping(value = "/checkOrderDetail")
    public Object checkOrderDetail(Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("订单表id");
            }
            OrderCheckInfo orderCheckInfo = IOmsOrderService.getCheckOrderDetail(id);
            return new CommonResult().success(orderCheckInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    /**
     * 对账单列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/checkList")
    public Object checkList(String orderSn, Integer checkStatus, BigDecimal minAmount, BigDecimal maxAmount,
                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            IPage<OrderCheckInfo> page = new Page<>();
            List<OrderCheckInfo> recordList = IOmsOrderService.getCheckList(orderSn, minAmount, maxAmount, checkStatus, pageNum, pageSize);
            long total = IOmsOrderService.gettCheckListTotal(orderSn, minAmount, maxAmount, checkStatus);
            page.setRecords(recordList);
            page.setSize(pageSize);
            page.setCurrent(pageNum);
            page.setTotal(total);
            return new CommonResult().success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "根据条件查询所有订单表列表", businessType = "列表", operatorType = "商户")
    @ApiOperation("根据条件查询所有订单表列表")
    @GetMapping(value = "/list")
    @PreAuthorize("hasAuthority('oms:OmsOrder:read')")
    public Object getOmsOrderByPage(OmsOrder entity, String submitTime,
                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        log.info("submitTime111:" + entity.getCreateTime());
        QueryWrapper<OmsOrder> wrapper = new QueryWrapper<OmsOrder>().orderByDesc("create_time");
        wrapper.eq("delete_status", 0);// 未删除
        log.info("submitTime:" + submitTime);
        if (submitTime != null) {
            // 开始时间起
            wrapper.apply(submitTime != null, "DATE_FORMAT(create_time, '%Y-%m-%d')" +
                    "= DATE_FORMAT( '" + submitTime + "', '%Y-%m-%d' )");
        }
//        // 结束时间止
//        wrapper.apply(params.get("reservationDatee") != null,"DATE_FORMAT( r.reservation_datee, '%Y-%m-%d' ) " +
//                " <= DATE_FORMAT( '"+params.get("reservationDatee")+"', '%Y-%m-%d' )");
        try {

            return new CommonResult().success(IOmsOrderService.page(new Page<OmsOrder>(pageNum, pageSize), wrapper));
        } catch (Exception e) {
            log.error("根据条件查询所有订单表列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    @SysAdminOperLog(MODULE = "oms", REMARK = "删除订单表")
    @ApiOperation("删除订单表")
    @GetMapping(value = "/delete/{id}")
    @PreAuthorize("hasAuthority('oms:OmsOrder:delete')")
    public Object deleteOmsOrder(@ApiParam("订单表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("订单表id");
            }
            if (IOmsOrderService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("删除订单表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "给订单表分配订单表")
    @ApiOperation("查询订单表明细")
    @GetMapping(value = "/{id}")
    public Object getOmsOrderById(@ApiParam("订单表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("订单表id");
            }
            OmsOrder coupon = IOmsOrderService.getById(id);
            coupon.setOrderItemList(orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", coupon.getId())));
            coupon.setHistoryList(omsOrderOperateHistoryMapper.selectList(new QueryWrapper<OmsOrderOperateHistory>().eq("order_id", coupon.getId())));
            // 查询发货单
            BillDelivery billDelivery = new BillDelivery();
            billDelivery.setOrderId(coupon.getId().toString());
            BillDelivery billDeliveryInfo = billDeliveryMapper.selectOne(new QueryWrapper<>(billDelivery));
            if (billDeliveryInfo != null) {
                coupon.setDeliveryNo(billDeliveryInfo.getDeliverySn());
            }
            // 查询收货天数
            OmsOrderSetting omsOrderSetting = omsOrderSettingMapper.selectOne(null);
            coupon.setAutoConfirmDay(omsOrderSetting.getConfirmOvertime());
            return new CommonResult().success(coupon);
        } catch (Exception e) {
            log.error("查询订单表明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }

    }

    @ApiOperation(value = "批量删除订单表")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.GET)
    @ResponseBody
    @SysAdminOperLog(MODULE = "pms", REMARK = "批量删除订单表")
    @PreAuthorize("hasAuthority('oms:OmsOrder:delete')")
    public Object deleteBatch(@RequestParam("ids") List<Long> ids) {
        if (ids == null || ids.size() == 0) {
            return new CommonResult().failed("参数不能为空！");
        }
        List<OmsOrder> list = new ArrayList<>();
        for (Long id : ids) {
            OmsOrder omsOrder = IOmsOrderService.getById(id);
            omsOrder.setDeleteStatus(1);
            list.add(omsOrder);
        }
        if (IOmsOrderService.updateBatchById(list)) {
            return new CommonResult().success();
        } else {
            return new CommonResult().failed();
        }
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "批量发货")
    @ApiOperation("批量发货")
    @RequestMapping(value = "/update/delivery", method = RequestMethod.POST)
    @ResponseBody
    public Object delivery(@RequestBody List<OmsOrderDeliveryParam> deliveryParamList) {
        int count = IOmsOrderService.delivery(deliveryParamList);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "批量发货")
    @ApiOperation("批量发货")
    @RequestMapping(value = "/delivery", method = RequestMethod.POST)
    @ResponseBody
    public Object singleDelivery(@RequestBody OmsOrderDeliveryParam deliveryParamList) {
        int count = IOmsOrderService.singleDelivery(deliveryParamList);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "批量关闭订单")
    @ApiOperation("批量关闭订单")
    @RequestMapping(value = "/update/close", method = RequestMethod.POST)
    @ResponseBody
    public Object close(@RequestParam("ids") List<Long> ids, @RequestParam String note) {
        int count = IOmsOrderService.close(ids, note);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "修改收货人信息")
    @ApiOperation("修改收货人信息")
    @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) {
        int count = IOmsOrderService.updateReceiverInfo(receiverInfoParam);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "修改订单费用信息")
    @ApiOperation("修改订单费用信息")
    @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) {
        int count = IOmsOrderService.updateMoneyInfo(moneyInfoParam);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @SysAdminOperLog(MODULE = "oms", REMARK = "备注订单")
    @ApiOperation("备注订单")
    @RequestMapping(value = "/update/note", method = RequestMethod.POST)
    @ResponseBody
    public Object updateNote(@RequestParam("id") Long id,
                             @RequestParam("note") String note,
                             @RequestParam("status") Integer status) {
        int count = IOmsOrderService.updateNote(id, note, status);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation(value = "查询订单列表")
    @GetMapping(value = "/order/list")
    public Object orderList(OmsOrder order,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "30") Integer pageSize,
                            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
        // 未删除
        order.setDeleteStatus(0);
        IPage<OmsOrder> page = null;
        if (order.getStatus() != null && order.getStatus() == 0) {
            page = IOmsOrderService.page(new Page<OmsOrder>(pageNum, pageSize), new QueryWrapper<OmsOrder>().orderByDesc("create_time").select(ConstansValue.sampleOrderList));
        } else {
            page = IOmsOrderService.page(new Page<OmsOrder>(pageNum, pageSize), new QueryWrapper<>(order).orderByDesc("create_time").select(ConstansValue.sampleOrderList));
        }
        for (OmsOrder omsOrder : page.getRecords()) {
            List<OmsOrderItem> itemList = orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", omsOrder.getId()).eq("type", AllEnum.OrderItemType.GOODS.code()));
            omsOrder.setOrderItemList(itemList);
        }
        return new CommonResult().success(page);
    }

    @ApiOperation(value = "查询订单物流")
    @GetMapping(value = "/getOrderLogistics")
    public Object orderLogistics() {
        String result = "[\n" +
                "    {name: '订单已提交，等待付款',time:'2017-04-01 12:00:00 '},\n" +
                "    {name: '订单付款成功',time:'2017-04-01 12:00:00 '},\n" +
                "    {name: '在北京市进行下级地点扫描，等待付款',time:'2017-04-01 12:00:00 '},\n" +
                "    {name: '在分拨中心广东深圳公司进行卸车扫描，等待付款',time:'2017-04-01 12:00:00 '},\n" +
                "    {name: '在广东深圳公司进行发出扫描',time:'2017-04-01 12:00:00 '},\n" +
                "    {name: '到达目的地网点广东深圳公司，快件将很快进行派送',time:'2017-04-01 12:00:00 '},\n" +
                "    {name: '订单已签收，期待再次为您服务',time:'2017-04-01 12:00:00 '}\n" +
                "  ]";
        return new CommonResult().success(result);
    }

    @GetMapping(value = "/getDeliveryExpressCompanyList")
    public Object getDeliveryExpressCompanyList() {
        List<OmsDeliveryExpressCompany> omsDeliveryExpressCompanyList = omsDeliveryExpressCompanyService.list(null);
        return new CommonResult().success(omsDeliveryExpressCompanyList);
    }

}
